<template>
  <div id="wrapper">
   <!-- <img id="logo" src="~@/assets/logo.png" alt="electron-vue"> -->
    <main>
      <!-- 左侧内容 -->
      <div class="left-side">
        <span class="title">
          EXCEL所在路径:
        </span>
        <!-- <system-information></system-information> -->
        
        <input class='pathinput' type='text' placeholder='请设置excel路径' disabled="disabled" :value=excelPath />
        <p><button class="chooseBt" @click='chooseExcel()'>选择</button></p>
        <br>

        <span class="title">
          JSON导出路径:
        </span>
        <!-- <system-information></system-information> -->
        <input class='pathinput' type='text' placeholder='请设置JSON导出路径' disabled="disabled" :value=jsonPath />
        <p><button class="chooseBt" @click='chooseJson()'>选择</button></p>
        <br>
        <hr>
        <br>
      </div>

      <!-- 右侧内容 -->
      <div class="right-side">
          <h3>输出日志:</h3>
          <div class='logList' id='logList'>
              <ul>
                <li v-for='(item) in logData' v-bind:key='item.text' :class='item.class'>
                    {{item.text}}
                </li>
              </ul>
          </div>
      </div>
    </main>
    <hr>
    <div class="bottom">
        <button @click="excelToJson()" style="font-size:32px">开始转换</button>
    </div>
    <div v-if="showUpdate">
     <updateUI></updateUI>
     </div>
  </div>
</template>

<script>  
let electron = require("electron");
import { BrowserWindow, ipcRenderer,app } from "electron";
var fs = require("fs");
var path = require("path");
import { remote } from "electron";
// import cr from "./content_replace.js";
import jc from "./json_convert.js";
import XLSX from "xlsx";
//import { setInterval, clearInterval } from "timers";
import updateUI from '@/components/updateUI/updateUI'

var config_file_path = "";
var self = null;
// import dialog  from 'electron';
export default {
  name: "landing-page",
  components: {updateUI},
  data() {
    return {
      excelPath: "",
      jsonPath: "",
      config: {},
      logData: [],
      desc: "选好目录，点击‘开始转换’",
      showUpdate:false
    };
  },

  beforeMount: function() {
    config_file_path = path.join(remote.app.getPath("userData"), "config.txt");
  },

  mounted() {
     self = this;
    ipcRenderer.on('message',(event,{message,data}) => {
      //console.log(data);
      if(message == "newversion")
      {
        self.showUpdate = true;
      }
      else if(message == "error")
      {
        alert("版本更新出现问题,请联系技术处理!\n错误信息:" +JSON.stringify(data));
      }
    });
   
    fs.exists(config_file_path, function(exist) {
      if (exist) {
        var content = fs.readFileSync(config_file_path, { encoding: "utf-8" });
        self.config = JSON.parse(content);
        self.excelPath = self.config.epath;
        self.jsonPath = self.config.jpath;

      }
    });
    // self.$options.methods.csvCheck();
  },
  methods: {
    // open(link) {
    //   this.$electron.shell.openExternal(link);
    // },

    clearLog() {
      self.logData.splice(0, self.logData.length);
    },

    addLog(text, isError) {
      var item = {};
      item.text = text;
      item.class = "log_normal";
      if (isError) item.class = "log_error";

      self.logData.push(item);
      var div = document.getElementById("logList");
      div.scrollTop = div.scrollHeight;
    },

    saveConfig() {
      fs.writeFileSync(config_file_path, JSON.stringify(self.config));
    },

    excelToJson() {
      var error = {};
      self.$options.methods.clearLog();

      var fileNames = [];
      var totalTime = +new Date();
      self.desc = "开始转换";
      console.log(self.desc)
      self.$options.methods.readDirSync(self.excelPath, fileNames);
      var index = 0;
      var ojpath = self.config.jpath; 
      var inter_id = setInterval(() => {
            if (index < fileNames.length) {
            var file_name = fileNames[index];
            var tail_index = file_name.indexOf(".");
            file_name = file_name.slice(0, tail_index);

            var beginTime = +new Date();
            var result = self.$options.methods.ExcelConvert(
              self.excelPath,
              fileNames[index],
              file_name,
              error
            );

            if (!result) {
              self.desc = "导出异常";
              clearInterval(inter_id);
              self.$options.methods.addLog(
                fileNames[index] + "导出错误：" + error.msg,
                true
              );
              return;
            }

            var now = +new Date();
            var logitem = fileNames[index] + "(" + (now - beginTime) + "ms)";
            self.$options.methods.addLog(logitem);
          index++;
        } else {
          clearInterval(inter_id);
          self.$options.methods.addLog("导出完成,总耗时:"+(+new Date() - totalTime) + "ms");
        }
      }, 0);

    },

    readDirSync(path, fileNames) {
      var self = this;
      var pa = fs.readdirSync(path);
      pa.forEach(function(ele, index) {
        var info = fs.statSync(path + "/" + ele);
        if (info.isDirectory()) {
       //   console.log("dir: " + ele);
          self.readDirSync(path + "/" + ele, fileNames);
        } else {
          //console.log("file: " + ele);
          if (ele.indexOf(".xlsx") > 0 && ele.indexOf('~')<0) fileNames.push(ele);
        }
      });
    },

    chooseExcel() {
      electron.remote.dialog.showOpenDialog(
        null,
        { properties: ["openFile", "openDirectory", "multiSelections"] },
        filePaths => {
          if (filePaths && filePaths.length > 0) {
            this.excelPath = filePaths[0];
            self.config.epath = this.excelPath;
            self.$options.methods.saveConfig();
          }
        }
      );
    },

    chooseJson() {
      electron.remote.dialog.showOpenDialog(
        null,
        { properties: ["openFile", "openDirectory", "multiSelections"] },
        filePaths => {
          if (filePaths && filePaths.length > 0) {
            this.jsonPath = filePaths[0];
            self.config.jpath = this.jsonPath;
            self.$options.methods.saveConfig();
          }
        }
      );
    },

    ExcelConvert(epath, fileName, json_path, err) {
      //var files = e.target.files;

      //console.log(fileName)
      var output_json_path = self.config.jpath; //cpath + "/json/";
      var path = epath + "/" + fileName;
      var workbook;

      //读取excel
      var data;
      try {
        data = fs.readFileSync(path, "binary"); //, function(err, data) {
      } catch (e) {
        err.msg = e.message;
        return false;
      }

      try {
        workbook = XLSX.read(data, { type: "binary" }); // 以二进制流方式读取得到整份excel表格对象
      } catch (e) {
        err.msg = "read error:" + e;
        return false;
      }

            // 遍历每张表读取
      for (var sheet in workbook.Sheets) {
        if (workbook.Sheets.hasOwnProperty(sheet)) {
          //转为json对象进行验证操作
          var json = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {
            header: 1,
            blankrows: false
          });
          //var replacePath = self.replacePath + "/" + fileName;

          //格式化
         // if (!cf.format(json, err)) return false;

          var jsonPath = output_json_path +"/"+ sheet +  ".json";
         
         
          var jsonString = jc.convert_to_string(json, err);
          if(err.msg)
            return false
          try {
              fs.writeFileSync(jsonPath, jsonString, {
                encoding: "utf-8"
              });
          } catch (e) {
            if (e) err.msg = e.message;
            return false;
          }

      //    break; // 如果只取第一张表，就取消注释这行
        }
      }
      return true;
    }
  }

};
</script>

<style>
@import url("https://fonts.googleapis.com/css?family=Source+Sans+Pro");

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: Arial, Helvetica, sans-serif;
}

li {
  list-style-type: none;
}

#wrapper {
  background: radial-gradient(
    ellipse at top left,
    rgba(255, 255, 255, 1) 40%,
    rgba(229, 229, 229, 0.9) 100%
  );
  height: 100vh;
  /* padding: 30px 30px; */
  width: 100vw;
}



main {
  display: flex;
  justify-content: space-between;
  height: 85vh;
  box-sizing: border-box;
  border: 1px solid rgb(56, 54, 54);
  padding: 20px;
}

main > div {
  flex-basis: 48%;
}

.left-side {
  display: flex;
  flex-direction: column;
  padding: 0;
}
.right-side {
  height: 100%;
  box-sizing: border-box;
}

.welcome {
  color: #555;
  font-size: 23px;
  margin-bottom: 10px;
}

.title {
  color: #2c3e50;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 6px;
  /* margin-left:20px; */
}

.pathinput {
  /* text-enable:false; */
  font-size: 16px;
}

.chooseBt {
  font-size: 16px;
  padding: 5px 10px;
  margin-top: 8px;
}

.bottom {
  display: flex;
  position: fixed;
  bottom: 1.6vh;
  width: 100%;
  left: 0;
  padding: 20px;
  justify-content: center;
  align-items: center;
  background-color: rgb(179, 166, 166);
  box-sizing: border-box;
  
}

.logList {
  height: 99%;
  width: 100%;
  padding: 10px 10px;

  overflow: scroll;
  overflow-x: hidden;
  border-left: 1px solid black;
  box-sizing: border-box;
}

.log_normal {
  color: black;
}
.log_error {
  color: red;
}

.hebing_div {
  box-sizing: border-box;
  border: 1px dotted gray;
}
</style>
